import ExamStatus from '@/components/type-of-exam/types/exam-status';
import { QuestDefaultApi } from '@/library/util/api';
import { defaultErrorHandler } from '@/library/util/error-handler';
import { defineStore } from 'pinia';
import DetailListAdapter from '../design/adpater/DetailListAdapter';
import QuestAdapter from '../design/adpater/QuestAdapter';
import { ExamItem, Questionaire } from '../design/types';
import Ipitem from './types/Ipitem';
interface AnalysisState {
  isLoading: boolean;

  ipMap: Map<string, number>;

  iplist: Ipitem[];

  /** 问卷信息 */
  questionaire: Questionaire;

  /** 题目信息 */
  content: ExamItem[];

  tips: string;
}
export const useAnalysisStore = defineStore({
  id: 'AnalysisStore',
  state: (): AnalysisState => ({
    isLoading: false,
    ipMap: new Map(),
    iplist: [],
    questionaire: new Questionaire(),
    content: [],
    tips: '',
  }),
  actions: {
    async getIps(queId: string) {
      try {
        this.isLoading = true;
        const result = await QuestDefaultApi.answerGetIPAddressListGet({
          queId: queId,
        });
        if (result) {
          this.iplist = [];
          this.ipMap.clear();
          for (const ip of result.address) {
            if (!this.ipMap.get(ip)) {
              this.ipMap.set(ip, 1);
            } else {
              let res = this.ipMap.get(ip) ?? 1;
              this.ipMap.set(ip, ++res);
            }
          }
        }

        this.ipMap.forEach((value, key) => {
          const res: Ipitem = {
            ip: key,
            sum: value,
          };

          this.iplist.push(res);
        });
      } catch (error) {
        defaultErrorHandler(error);
      } finally {
        this.isLoading = false;
      }
    },

    /**
     * 获取作答结果
     * @param queId
     */
    async getResult(queId: string) {
      try {
        this.isLoading = true;

        const count = await QuestDefaultApi.answerAnswerCountGet({
          queId: queId,
        });

        if (!count) {
          this.tips = '当前问卷无作答！';
          throw new Error('当前问卷无作答！');
        }

        const result = await QuestDefaultApi.answerResultGet({
          queId: queId,
        });

        if (result) {
          this.content = [];
          this.questionaire = new Questionaire();

          this.content = new DetailListAdapter().compose(
            result.results,
            ExamStatus.Statistics,
          );

          this.questionaire = new QuestAdapter().compose(result);
        }

        // console.log(this.content);
      } catch (error) {
        defaultErrorHandler(error);
      } finally {
        this.isLoading = false;
      }
    },

    reSetTips() {
      this.tips = '';
    },
  },
});
